<?php
/**
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * PHP Version 5
 *
 * @category ApiController
 * @package  Namespace
 * @author   Wang Zhaogang <Wang Zhaogang@babamaiche.com>
 * @file     ApiController.php
 * @date     2016/4/25
 * @time     20:51
 * @license  http://chedamai.cn/ License
 * @link     http://chedamai.cn/
 */

namespace app\controllers;

use app\components\Go;
use app\components\Plate;
use app\components\Shape;
use yii;
use yii\log\Logger;
/**
 * The ApiController class is used for ***
 *
 * @category ApiController
 * @package  Namespace
 * @author   Wang Zhaogang <Wang Zhaogang@babamaiche.com>
 * @class    ApiController
 * @date     2016/4/25
 * @time     20:51
 * @license  http://chedamai.cn/ License
 * @link     http://chedamai.cn/
 */

class ApiController extends \yii\web\Controller
{
    public function beforeAction($action) {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        Go::initShapes();
        return parent::beforeAction($action);
    }
    public function actionEcho() {
        return ['Hello' => 'world!'];
    }

    public function actionGetAllShapes() {
        return ['success' => true, 'data' =>
            array_map(function ($a) {return $a->toArray();}, Go::$allShapes)
        ];
    }
    public function actionGo($width, $selectShapes) {
        $width = intval($width);
        if ($width < 3 || $width > 12) {
            return ['success' => false, 'message' => 'Invalid size.'];
        }
        if (count($selectShapes) > 12) {
            return ['success' => false, 'message' => 'Invalid count.'];
        }
        $selectShapeIds = array_map(function ($s) {return intval($s);},
            explode(',', $selectShapes));
        return Go::findPath($width, $selectShapeIds);

    }
    public function actionTest() {
        $shape = new Shape(2, 4, 2, [
            [1,1,1,1],
            [0,0,1,0],
        ], "#996600");
        $ret = [];
        while($shape->nextPlacement()) {
            Yii::getLogger()->log('TEST placement：' . print_r($shape->getPlacement(), true), Logger::LEVEL_INFO);
            Yii::getLogger()->log('TEST data：' . Shape::formatArray($shape->toArray()['data']), Logger::LEVEL_INFO);
        }
        return $ret;

    }
}